package org.idea.ietty.action.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class RpcServer {
    public void export(Object service,int port){
        if(service==null || port<0 || port>65535){
            throw new RuntimeException("param is error");
        }
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            while (true){
                System.out.println("=========服务暴露========");
                final Socket socket = serverSocket.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                            String methodName = objectInputStream.readUTF();
                            Class<?>[] parameterTypes = (Class<?>[]) objectInputStream.readObject();
                            Object[] args = (Object[]) objectInputStream.readObject();
                            Method method = service.getClass().getMethod(methodName,parameterTypes);
                            Object result = method.invoke(service,args);
                            output.writeObject(result);
                        } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}